<template>
    <a-form ref="formRef" :model="model" :rules="rules" v-bind="formItemLayout">
        <a-row :gutter="10">
            <a-col :span="12">
                <a-form-item label="适用范围" name="scopeApplication">
                    <a-tree
                        v-model:checkedKeys="model.scopeApplication"
                        :tree-data="treeData"
                        default-expand-all 
                        checkable 
                        @check="handleTreeCheck">
                    </a-tree>
                </a-form-item>
            </a-col>
        </a-row>
    </a-form>
</template>

<script lang='ts' setup>
    import { ref } from 'vue';

    defineOptions({
        /** 适用范围表单 */
        name: 'FileApplicationScopeForm',
    });

    const model = defineModel({
        type: Object, // 类型检查
        required: true, // 是否必填
        // 默认值
        default: {
            scopeApplication: [],
        }, 
    });
    
    const formRef = ref();

    const rules = ref({
        scopeApplication: [{ required: true, type: 'array', message: '请选择适用范围', trigger: ['change'] }],
    })
    // "emit('update:modelValue', $event.target.value)"
    const formItemLayout = ref({
        labelCol: { span: 6 },
        wrapperCol: { span: 18 },
    });

    const treeData = ref([
            {
                title: 'MTY',
                key: '0-0',
                children: [
                    {
                        title: 'Western QMS',
                        key: '0-0-0',
                    },
                    {
                        title: 'CMI',
                        key: '0-0-1',
                    },
                    {
                        title: 'RH',
                        key: '0-0-2',
                    },
                    {
                        title: 'Automation',
                        key: '0-0-3',
                    },
                    {
                        title: 'Software solutions',
                        key: '0-0-4',
                    },
                ]
            }
        
    ]);
    // tree check事件处理，check操作本身不会触发change事件，从而触发表单校验更新，需要手动调用表单校验
    function handleTreeCheck() {
        formRef.value.validateFields(['scopeApplication']);
    }

    function validate() {
        return new Promise((resolve) => {
            formRef.value.validate().then((values) => {
                console.log('values', values);
                resolve({valid: true, values});
            })
            .catch(error => {
                console.log('error', error);
                resolve({valid: false, values: error?.values});
            });
        })
    }
    // 对外暴露属性方法
    defineExpose({
        validate,
    });

</script>

<style scoped lang="less">
</style>